<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>商品详情</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            padding: 10px 20px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #ff6666;
        }

        .nav {
            display: flex;
            align-items: center;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            margin: 0 10px;
        }

        .nav .welcome {
            color: #999;
            margin: 0 10px;
        }

        .nav .logout {
            color: #ff6666;
            cursor: pointer;
            margin: 0 10px;
        }

        footer {
            text-align: center;
            padding: 10px;
            background-color: #333;
            color: #999;
            margin-top: 40px;
        }

        main {
            width: 90%;
            max-width: 1200px;
            margin: 40px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 4px;
        }

        .content-wrapper {
            display: flex;
            flex-wrap: wrap;
            gap: 40px;
        }

        .image-section {
            display: flex;
            align-items: flex-start;
            gap: 20px;
        }

        .product-thumbnail {
            width: 300px;
            height: 300px;
            border: 1px solid #eee;
            position: relative;
            overflow: hidden;
        }

        .product-thumbnail img {
            width: 100%;
            height: 100%;
            display: block;
        }

        .magnifier-indicator {
            width: 150px;
            height: 150px;
            background: rgba(255, 255, 255, 0.6);
            border: 1px solid #ccc;
            position: absolute;
            display: none;
            pointer-events: none;
        }

        .magnifier-box {
            width: 400px;
            height: 400px;
            border: 1px solid #eee;
            overflow: hidden;
            display: none;
            position: relative;
        }

        .magnifier-box img {
            width: 800px;
            height: 800px;
            position: absolute;
            top: 0;
            left: 0;
            object-fit: cover;
        }

        .product-info {
            flex: 1;
            min-width: 300px;
            padding: 20px 0;
        }

        .product-info h2 {
            font-size: 24px;
            color: #333;
            margin-bottom: 15px;
        }

        .product-info .price {
            font-size: 26px;
            color: #ff6666;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .product-info p {
            color: #666;
            line-height: 1.8;
            margin-bottom: 30px;
            font-size: 16px;
        }

        .product-info button {
            background-color: #ff6666;
            color: #fff;
            border: none;
            padding: 12px 30px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .product-info button:hover {
            background-color: #e05555;
        }
    </style>
</head>

<body>
    <div id="navbar">
        <header>
            <div class="logo">闪购</div>
            <div class="nav">
                <a href="index.html">首页</a>
                <a href="cart.html">购物车 <span id="cartCount">0</span></a>
                <span class="welcome">欢迎, <span id="username">游客</span></span>
                <span class="logout" onclick="logout()">退出登录</span>
            </div>
        </header>
    </div>

    <main>
        <div class="content-wrapper">
            <div class="image-section">
                <div class="product-thumbnail">
                    <img src="" alt="商品主图" id="mainImg" />
                    <div class="magnifier-indicator" id="magnifierIndicator"></div>
                </div>
                <div class="magnifier-box" id="magnifierBox">
                    <img src="" alt="放大图" id="magnifiedImg" />
                </div>
            </div>

            <div class="product-info">
                <h2 id="productName"></h2>
                <div class="price" id="productPrice"></div>
                <p id="productDesc"></p>
                <button onclick="addToCart()">加入购物车</button>
            </div>
        </div>
    </main>

    <footer>
        <p>©2025 闪购</p>
    </footer>

    <script>
        function initNav() {
            // 显示用户名
            const usernameSpan = document.getElementById('username');
            const storedUsername = localStorage.getItem('username');
            usernameSpan.textContent = storedUsername || '游客';

            // 更新购物车数量
            updateCartCount();
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('username');
            window.location.href = 'login.html';
        }

        // 更新购物车数量显示
        function updateCartCount() {
            const username = localStorage.getItem('username');
            if (!username) {
                document.getElementById('cartCount').textContent = '0';
                return;
            }

            // 从全局购物车数据中获取当前用户的购物车
            const allCarts = JSON.parse(localStorage.getItem('allCarts') || '{}');
            const userCart = allCarts[username] || [];
            const totalCount = userCart.reduce((sum, item) => sum + (item.quantity || 1), 0);

            document.getElementById('cartCount').textContent = totalCount;
        }

        // 初始化导航
        initNav();

        // 当前页面的商品信息
        let currentProduct = null;

        window.onload = function () {
            // 加载商品详情
            loadProductDetail();
        }

        // 加载商品详情
        function loadProductDetail() {
            const urlParams = new URLSearchParams(window.location.search);
            const productId = urlParams.get('id');

            // 从localStorage获取商品数据
            const products = JSON.parse(localStorage.getItem('product') || '[]');
            const product = products.find(p => p.id == productId);

            if (product) {
                currentProduct = product;

                // 渲染商品信息
                document.getElementById('productName').textContent = product.name;
                document.getElementById('productPrice').textContent = `¥${product.price}`;
                document.getElementById('productDesc').textContent = product.description;

                const mainImg = document.getElementById('mainImg');
                const magnifiedImg = document.getElementById('magnifiedImg');
                mainImg.src = product.image;
                magnifiedImg.src = product.image;

                // 初始化放大镜功能
                initMagnifier();
            } else {
                alert('未找到该商品信息');
            }
        }

        function initMagnifier() {
            const thumbnail = document.querySelector('.product-thumbnail');
            const indicator = document.getElementById('magnifierIndicator');
            const magnifierBox = document.getElementById('magnifierBox');
            const magnifiedImg = document.getElementById('magnifiedImg');

            // 鼠标移入
            thumbnail.addEventListener('mouseenter', () => {
                indicator.style.display = 'block';
                magnifierBox.style.display = 'block';
            });

            // 鼠标移动
            thumbnail.addEventListener('mousemove', (e) => {
                const rect = thumbnail.getBoundingClientRect();
                const x = e.clientX - rect.left;
                const y = e.clientY - rect.top;

                // 计算指示器位置
                const maxLeft = rect.width - indicator.offsetWidth;
                const maxTop = rect.height - indicator.offsetHeight;
                const left = Math.max(0, Math.min(x - indicator.offsetWidth / 2, maxLeft));
                const top = Math.max(0, Math.min(y - indicator.offsetHeight / 2, maxTop));

                indicator.style.left = `${left}px`;
                indicator.style.top = `${top}px`;

                // 计算放大图位置
                const scaleX = left / maxLeft;
                const scaleY = top / maxTop;
                const imgMaxLeft = magnifiedImg.offsetWidth - magnifierBox.offsetWidth;
                const imgMaxTop = magnifiedImg.offsetHeight - magnifierBox.offsetHeight;

                magnifiedImg.style.left = `-${scaleX * imgMaxLeft}px`;
                magnifiedImg.style.top = `-${scaleY * imgMaxTop}px`;
            });

            // 鼠标移出
            thumbnail.addEventListener('mouseleave', () => {
                indicator.style.display = 'none';
                magnifierBox.style.display = 'none';
            });
        }

        // 加入购物车
        function addToCart() {
            if (!currentProduct) return;

            const username = localStorage.getItem('username');
            if (!username) {
                // 未登录用户提示登录
                if (confirm('请先登录才能添加商品到购物车，是否前往登录？')) {
                    window.location.href = 'login.html';
                }
                return;
            }

            // 获取所有用户的购物车数据
            const allCarts = JSON.parse(localStorage.getItem('allCarts') || '{}');
            // 获取当前用户的购物车
            const userCart = allCarts[username] || [];

            // 检查商品是否已在购物车中
            const existingItemIndex = userCart.findIndex(item => item.id === currentProduct.id);
            if (existingItemIndex > -1) {
                // 已存在则增加数量
                userCart[existingItemIndex].quantity = (userCart[existingItemIndex].quantity || 1) + 1;
                alert(`已将${currentProduct.name}添加到购物车，当前数量：${userCart[existingItemIndex].quantity}`);
            } else {
                // 不存在则添加新商品
                userCart.push({
                    id: currentProduct.id,
                    name: currentProduct.name,
                    price: currentProduct.price,
                    image: currentProduct.image,
                    quantity: 1
                });
                alert(`${currentProduct.name}已成功添加到购物车！`);
            }

            // 保存更新后的购物车数据
            allCarts[username] = userCart;
            localStorage.setItem('allCarts', JSON.stringify(allCarts));

            // 更新导航栏中的购物车数量
            updateCartCount();
        }
    </script>
</body>

</html>